import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
// 1.导入组件
import login from '@/views/user/login.vue' 
import layout from '@/views/layout.vue'
import home from '@/views/home/home.vue'
import qa from '@/views/qa/qa.vue'
import movie from '@/views/movie/movie.vue'
import user from '@/views/user/user.vue'
import notfound from '@/views/notfound/notfound.vue'
import edit from '@/views/user/edit.vue'
import article from '@/views/home/article.vue'
import search from '@/views/home/search.vue'
import searchResult from '@/views/home/searchResult.vue'
import student from '@/views/user/student.vue'

const routes = [
  {
    name:'login',
    path:'/login',
    component:login
  },
  {
    name:'edit',
    path:'/edit',
    component:edit
  },
  {
    name:'myarticle',
    path:'/article',
    component:article
  },
  {
    name:'search',
    path:'/search',
    component:search
  },
  {
    name:'searchResult',
    path:'/searchResult',
    component:searchResult
  },
  {
    name:'student',
    path:'/student',
    component:student
  },
  {
    name:'layout',
    path:'/',
    component:layout,
    children:[
      {
        name:'home',
        path:'/home',
        component:home
      },
      {
        name:'qa',
        path:'/qa',
        component:qa
      }, 
       {
        name:'movie',
        path:'/movie',
        component:movie
      }, 
       {
        name:'user',
        path:'/user',
        component:user,
      // 给user添加路由元信息
        meta:{ isLogin:true }
      },
      {
        path:'/',
        redirect:'/home'
      }
    ]
  },
  {
  name:'notfound',
  path:'/notfound',
  component:notfound
  },
  {
    path:'*',
    redirect:'/notfound'
  }
]

const router = new VueRouter({
  routes
})
// 路由导航守卫:一定要写在创建路由对象的后面
// 导入token
import { getToken  } from '@/utils/token.js'
router.beforeEach((to,from,next)=>{
  // to:目标路由,要跳到哪里去
  console.log(to);
  // from:来源路由,从哪个页面跳转过来
  console.log(from);
  // next():允许正常跳转
  // 1.路由导航守卫中一定要跳转next(),如果不调用,路由无法跳转
  // 2.next():不加参数,通过检查,允许跳转
  // 3.next({path:'路径'}):检查不通过,进行拦截,跳转到指定页面

  // 判断to页面是否需要登录检查
  // if( to.meta.isLogin){
  //   // 判断用户是否登录
  //   if( getToken() ){
  //     next()
  //   }else{
  //     // 未登录,跳转登录页
  //     next({path:'/login'})
  //   }
  // }else{
  //   next()
  // }

  
    //判断用户没有没有登录
    if( to.meta.isLogin && !getToken() ){
      //没有登录，则跳转登录页
      next({path:'/login'})
      // 设置定时器,清除报错
      setTimeout(()=>{
        console.clear()
      })
    }else{
      //有登录，正常跳转
      next()
    }
})

export default router
